# By default CMAKE_PREFIX_PATH, which contains the VCPKG_INSTALLED_DIR, will be
# appended to the pkg-config search path. Because it is appending and not
# prepeding, system packages may be found first. Specifically prepending the
# vcpkg_pkg_config_path to ENV{PKG_CONFIG_PATH} will prioritize the vcpkg
# packages.
if(NOT VCPKG_PREFER_SYSTEM_LIBS)
  if(NOT DEFINED CMAKE_BUILD_TYPE OR CMAKE_BUILD_TYPE MATCHES
                                     "^[Dd][Ee][Bb][Uu][Gg]$")
    set(path_suffix "/debug")
  else()
    set(path_suffix "")
  endif()
  set(backup_env_pkg_config_path "$ENV{PKG_CONFIG_PATH}")

  # Compute the installation prefix relative to this file.
  get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
  get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
  get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
  if(_IMPORT_PREFIX STREQUAL "/")
    set(_IMPORT_PREFIX "")
  endif()

  # libdpdk.pc and libdpdk-libs.pc are installed to this path
  set(ENV{PKG_CONFIG_PATH}
      "${_IMPORT_PREFIX}${path_suffix}/lib/pkgconfig:$ENV{PKG_CONFIG_PATH}"
  )
else()
  unset(backup_env_pkg_config_path)
endif()

if(DEFINED ENV{PKG_CONFIG})
  set(PKG_CONFIG_EXECUTABLE "$ENV{PKG_CONFIG}")
else()
  set(PKG_CONFIG_EXECUTABLE "@PKGCONFIG@")
endif()
find_package(PkgConfig REQUIRED)
pkg_check_modules(LIBDPDK REQUIRED libdpdk>=@PORT_VERSION@)

if(DEFINED backup_env_pkg_config_path)
  set(ENV{PKG_CONFIG_PATH} "${backup_env_pkg_config_path}")
endif()

mark_as_advanced(
  LIBDPDK_STATIC_INCLUDE_DIRS
  LIBDPDK_INCLUDE_DIRS
  LIBDPDK_STATIC_CFLAGS
  LIBDPDK_CFLAGS
  LIBDPDK_STATIC_LDFLAGS
  LIBDPDK_LDFLAGS
  LIBDPDK_VERSION)

add_library(unofficial::@PORT@::dpdk INTERFACE IMPORTED)
unset(LIBDPDK_FOUND)

if(@VCPKG_LIBRARY_LINKAGE@ STREQUAL "static")
  set(INCLUDE_DIRS "${LIBDPDK_STATIC_INCLUDE_DIRS}")
  # https://bechsoftware.com/2021/12/05/configuring-dpdk-projects-with-cmake/
  target_compile_options(unofficial::@PORT@::dpdk
                         INTERFACE ${LIBDPDK_STATIC_CFLAGS})
  target_link_libraries(unofficial::@PORT@::dpdk
                        INTERFACE ${LIBDPDK_STATIC_LDFLAGS})
else()
  set(INCLUDE_DIRS "${LIBDPDK_INCLUDE_DIRS}")
  target_compile_options(unofficial::@PORT@::dpdk INTERFACE ${LIBDPDK_CFLAGS})
  target_link_libraries(unofficial::@PORT@::dpdk INTERFACE ${LIBDPDK_LDFLAGS})
endif()

target_include_directories(unofficial::@PORT@::dpdk INTERFACE ${INCLUDE_DIRS})

find_package_handle_standard_args(
  unofficial-@PORT@
  REQUIRED_VARS INCLUDE_DIRS LIBDPDK_STATIC_CFLAGS LIBDPDK_CFLAGS
                LIBDPDK_STATIC_LDFLAGS LIBDPDK_LDFLAGS
  VERSION_VAR LIBDPDK_VERSION)
